package javabase.demo03;

public class VolatilePractice {

    private static volatile boolean running = true;
    private static volatile int count = 0;

    public static void main(String[] args) throws InterruptedException {
        // 1. 保证可见性
        Thread t1 = new Thread(() -> {
            System.out.println("线程1启动");
            while (running) {
                // 空循环
            }
            System.out.println("线程1结束");
        });

        t1.start();
        Thread.sleep(100);
        running = false; // 主线程修改running，t1线程可见
        System.out.println("主线程设置running为false");

        // 2. 不保证原子性
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    count++; // 即使volatile也不保证原子性
                }
            }).start();
        }

        Thread.sleep(2000);
        System.out.println("volatile计数: " + count + " (期望: 10000)");

        // 3. 禁止指令重排
        demonstrateReorderPrevention();
    }

    // 演示volatile禁止指令重排
    private static void demonstrateReorderPrevention() {
        System.out.println("\n=== volatile禁止指令重排 ===");

        // 单例模式中的双重检查锁定
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();

        System.out.println("单例实例相同: " + (instance1 == instance2));
    }
}

// 单例模式：双重检查锁定 + volatile
class Singleton {
    private static volatile Singleton instance;

    private Singleton() {
        System.out.println("Singleton实例化");
    }

    public static Singleton getInstance() {
        if (instance == null) { // 第一次检查
            synchronized (Singleton.class) {
                if (instance == null) { // 第二次检查
                    instance = new Singleton(); // volatile防止指令重排
                }
            }
        }
        return instance;
    }
}
